﻿using System.Threading;
using System.Threading.Tasks;
using GreenPipes;
using MassTransit;
using MassTransit.EntityFrameworkCoreIntegration.Saga;
using MassTransit.Registration;
using MassTransitDemo.TrackingService.Consumers;
using MassTransitDemo.TrackingService.Models;
using Microsoft.Extensions.Hosting;

namespace MassTransitDemo.TrackingService
{
    public class ResponseHostedService : IHostedService
    {
        IBusControl _busControl;

        public async Task StartAsync(CancellationToken stoppingToken)
        {
            var rabbitMQAddress = "119.3.001.001";
            var metricsQueueName = "routing_slip_metrics";
            var activityMetricsQueueName = "routing_slip_activity_metrics";
            var stateQueueName = "routing_slip_state";

            var _metrics = new RoutingSlipMetrics("Routing Slip");
            var _activityMetrics = new RoutingSlipMetrics("Validate Activity");
            var _machine = new RoutingSlipStateMachine();

            //var _repository = new EntityFrameworkSagaRepository<RoutingSlipState>();
            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                x.Host(rabbitMQAddress, 5672, "masstransitdemo", h =>
                {
                    h.Username("masstransitdemo");
                    h.Password("masstransitdemo@test");
                });

                x.ReceiveEndpoint(metricsQueueName, e =>
                {
                    e.PrefetchCount = 100;
                    e.UseRetry(r => r.None());
                    e.Consumer(() => new RoutingSlipMetricsConsumer(_metrics));
                });

                x.ReceiveEndpoint(activityMetricsQueueName, e =>
                {
                    e.PrefetchCount = 100;
                    e.UseRetry(r => r.None());
                    e.Consumer(() => new RoutingSlipActivityConsumer(_activityMetrics, "Validate"));
                });

                //x.ReceiveEndpoint(stateQueueName, e =>
                //{
                //    e.PrefetchCount = 8;
                //    e.UseConcurrencyLimit(1);
                //    e.StateMachineSaga(_machine, _repository);
                //});
            });

            await _busControl.StartAsync();
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            _busControl?.Stop();
            return Task.CompletedTask;
        }
    }
}
